package com.insurance.modules.claim.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insurance.common.utils.AmountUtils;
import com.insurance.common.utils.BeanUtils;
import com.insurance.common.utils.PageUtils;
import com.insurance.common.utils.Query;
import com.insurance.modules.claim.constants.ClaimConstants;
import com.insurance.modules.claim.constants.EntityTypeEnum;
import com.insurance.modules.claim.dao.TreatmentInfoDao;
import com.insurance.modules.claim.entity.*;
import com.insurance.modules.claim.service.*;
import com.insurance.modules.claim.vo.request.TreatmentInfoSaveReq;
import com.insurance.modules.claim.vo.response.TreatmentInfoRsp;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("treatmentInfoService")
public class TreatmentInfoServiceImpl extends ServiceImpl<TreatmentInfoDao, TreatmentInfoEntity> implements TreatmentInfoService {

    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private ClaimSettlementService claimSettlementService;
    @Autowired
    private ClaimCaseService claimCaseService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TreatmentInfoEntity> page = this.page(
                new Query<TreatmentInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public TreatmentInfoRsp getByCsId(String csId) {
        LambdaQueryWrapper<TreatmentInfoEntity> treatmentQueryWrapper = Wrappers.lambdaQuery();
        treatmentQueryWrapper.eq(TreatmentInfoEntity::getCsId, csId);
        TreatmentInfoEntity treatmentInfo = this.getOne(treatmentQueryWrapper);
        if (treatmentInfo == null) {
            return new TreatmentInfoRsp();
        }
        // 金额分转元
        TreatmentInfoRsp rsp = BeanUtils.conversion(treatmentInfo, TreatmentInfoRsp.class);
        rsp.setPayAdvanceAmountYuan(AmountUtils.fenToYuanBigDecimal(rsp.getPayAdvanceAmount()));
        rsp.setInvoiceAmountYuan(AmountUtils.fenToYuanBigDecimal(rsp.getInvoiceAmount()));
        rsp.setFamilyWantAmountYuan(AmountUtils.fenToYuanBigDecimal(rsp.getFamilyWantAmount()));

        rsp.setFiles(fileInfoService.listByBusinessIdAndAttachment(csId, null, EntityTypeEnum.settlement));
        return rsp;
    }

    @Override
    @Transactional
    public void saveTreatmentAndFile(TreatmentInfoSaveReq req) {
        String csId = req.getCsId();
        saveOrUpdateTreatmentInfo(req);
        List<FileInfoEntity> files = req.getFiles();
        if(CollectionUtils.isNotEmpty(files)){
            for (FileInfoEntity file : files) {
                file.setBusinessId(csId);
                file.setCreateTime(req.getUpdateTime());
                file.setCreateBy(req.getUpdateBy());
            }
            //批量保存
            fileInfoService.saveBatch(files);
        }
        List<String> deleteFiles = req.getDeleteFiles();
        if(CollectionUtils.isNotEmpty(deleteFiles)){
            //根据id批量删除
            fileInfoService.removeByIds(deleteFiles);
        }
        // 修改理赔状态
        if (req.getSendCorpTime() != null) {
            updateCaseStatus2Commit(req.getCsId());
        }
    }

    /**
     * 案件理赔表理赔记录的状态为受理中（case_status = 1）时，更新为已提交保司（case_status = 2）
     *
     * @param csId
     */
    private void updateCaseStatus2Commit(String csId) {
        ClaimSettlementEntity claimSettlement = claimSettlementService.getById(csId);
        if (ClaimConstants.CLAIM_STATUS_ACCEPT.equals(claimSettlement.getCaseStatus())) {
            // 更新案件理赔表
            claimSettlement.setCaseStatus(ClaimConstants.CLAIM_STATUS_COMMIT);
            claimSettlementService.updateById(claimSettlement);

            // 更新案件表冗余字段
            LambdaUpdateWrapper<ClaimCaseEntity> claimCaseUpdateWrapper = Wrappers.lambdaUpdate();
            claimCaseUpdateWrapper.eq(ClaimCaseEntity::getId, claimSettlement.getCaseId());
            if (ClaimConstants.SETTLEMENT_ORDER_FIRST.equals(claimSettlement.getSettlementOrder())) {
                // 首次理赔
                claimCaseUpdateWrapper.set(ClaimCaseEntity::getFirstStatus, ClaimConstants.CLAIM_STATUS_COMMIT);
            } else {
                // 二次理赔
                claimCaseUpdateWrapper.set(ClaimCaseEntity::getSecondStatus, ClaimConstants.CLAIM_STATUS_COMMIT);
            }
            claimCaseUpdateWrapper.set(ClaimCaseEntity::getCaseStatus, ClaimConstants.CASE_STATUS_COMMIT);
            claimCaseService.update(claimCaseUpdateWrapper);
        }
    }

    /**
     * 保存诊疗信息
     */
    private void saveOrUpdateTreatmentInfo(TreatmentInfoSaveReq req) {
        TreatmentInfoEntity treatmentInfo = BeanUtils.conversion(req, TreatmentInfoEntity.class);
        // 金额元转分
        treatmentInfo.setPayAdvanceAmount(AmountUtils.yuanToFenLong(req.getPayAdvanceAmountYuan()));
        treatmentInfo.setInvoiceAmount(AmountUtils.yuanToFenLong(req.getInvoiceAmountYuan()));
        treatmentInfo.setFamilyWantAmount(AmountUtils.yuanToFenLong(req.getFamilyWantAmountYuan()));

        this.saveOrUpdate(treatmentInfo);
    }

}